package unimelb.filesync.common.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class NetworkConnection {
    private Socket socket;

    private PrintWriter out;

    private BufferedReader in;

    protected NetworkConnection() {

    }

    public NetworkConnection(Socket socket) {
        super();
        this.socket = socket;
        try {
            out = new PrintWriter(this.socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void writeString(String msg) {
        out.println(msg);
    }

    public String readString() {
        try {
            return in.readLine();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void close() {
        out.close();
        try {
            in.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public String getDestinationIp() {
        return socket.getInetAddress().getHostAddress();
    }
}
